/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.exec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

/**
 * 封装一些关于本机进程调用的常用方法。 实现使用了apache-commons exec，详见：
 * http://commons.apache.org/proper/commons-exec/tutorial.html
 * http://commons.apache.org/proper/commons-exec/apidocs
 *
 * @author Administrator
 */
public class ExeUtil {

    private static final Logger logger = Logger.getLogger(ExeUtil.class.getName());
    private static final int exitvalue = 0;

    /**
     *
     * @param command 命令行字符串，如："resources/test.bat"
     * @param timeout 超时时间（毫秒），若设置为不超时使用：ExecuteWatchdog.INFINITE_TIMEOUT
     * @return "屏幕"输出结果，执行失败返回null
     * @throws TimeoutExecuteException
     * @throws ExecuteException
     */
    public static String executeLocalCmd(String command, long timeout) throws ExecuteTimeoutException, ExecuteException {


        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

        //解析命令行
        CommandLine commandline = CommandLine.parse(command);

        DefaultExecutor exec = new DefaultExecutor();

        //设置正常退出系统返回值标识，一般系统为0
        exec.setExitValue(exitvalue);

        //构建输出流处理对象
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);

        //在执行器上设置输出流处理对象
        exec.setStreamHandler(streamHandler);

        //构建执行超时看门狗
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);

        //在执行器上设置执行超时看门狗
        exec.setWatchdog(watchdog);

        try {

            exec.execute(commandline);
        }
        catch (ExecuteException ex) {

            if (watchdog.killedProcess()) {

                //判断是否是执行超时
                throw new ExecuteTimeoutException("The process execute timed out.", ex.getExitValue(), ex);

            } else {

                throw ex;
            }
        }
        catch (IOException ex) {

            throw new ExecuteException("The process execute timed out.", 1, ex);

        }

        String out = outputStream.toString();

        String error = errorStream.toString();
        logger.info("Error:" + error);

        return out + error;


    }

    public static void main(String args[]) {

        String s1 = "src/test/resources/test.bat 1>test.out"; //只将标准输出重定向到文件，“屏幕”只返回标准错误
        String s2 = "src/test/resources/test.bat 1>test.log 2>&1 ";//标准输出和标准错误重定向到同一文件，“屏幕”返回空
        String s3 = "src/test/resources/test.bat 1>test.out 2>test.err";//标准输出和标准错误重定向到不同文件，“屏幕”返回空
        String s4 = "src/test/resources/test.bat ";

        String ret = null;
        try {
            //不限制超时
            ret = executeLocalCmd(s4, ExecuteWatchdog.INFINITE_TIMEOUT);
            //限制1秒超时
            //ret = executeLocalCmd(s2, 1000);
        }
        catch (ExecuteTimeoutException ex) {
            logger.log(Level.SEVERE, "执行超时", ex);

        }
        catch (ExecuteException ex) {
            logger.log(Level.SEVERE, "执行失败，脚本中可能存在错误", ex);

        }

        logger.info("ret:" + ret);

    }
}
